import { useEffect, useMemo } from 'react'
import { Badge, Button, Input, Modal, Tooltip } from 'antd'
import { DeleteOutlined, FormOutlined } from '@ant-design/icons'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { AddOrEditMsgDrawer } from './AddOrEditMsgDrawer'
import { channelMap, enableStatusMap, eventTypeMap, receiveObjMap, sendTypeMap, typeMap } from './const'
import { IMsgList, TCol, TParams } from './interface'
import { useBoundStore } from './store'
import { useMsgManageList } from './useMsgManageList'
import { popupSlot } from './utils'
import styles from './styles.module.less'

const ActionCell = ({ data }: TParams) => {
  const delMsg = useBoundStore(v => v.delMsg)
  const getData = useBoundStore(v => v.getData)
  if (data == null) return
  return (
    <div>
      <Tooltip title="编辑">
        <Button
          type="link"
          icon={<FormOutlined />}
          onClick={() => {
            AddOrEditMsgDrawer.open({
              messageId: data.messageId,
              onSuccess: () => getData({ page: 1 }),
            })
          }}
        />
      </Tooltip>
      <Tooltip title="删除">
        <Button
          onClick={() => {
            Modal.confirm({
              title: '确认要删除吗？',
              onOk: () => delMsg(data.messageId),
            })
          }}
          type="link"
          danger
          icon={<DeleteOutlined />}
        />
      </Tooltip>
    </div>
  )
}

const Cell = (p: TParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    // 启用状态
    case 'enableFlag': {
      const { value } = p as TParams<'enableFlag'>
      if (value == null) return
      return <Badge color={p.value === 1 ? 'green' : $CSS_VAR.statusDefault} text={enableStatusMap[value]} />
    }
    // 渠道类型
    case 'channelType': {
      const { value } = p as TParams<'channelType'>
      if (value == null) return
      return <div>{channelMap[value]}</div>
    }
    // 触发时间
    case 'eventType': {
      const { value } = p as TParams<'eventType'>
      if (value == null) return
      return <div>{eventTypeMap[value]}</div>
    }
    // 接受对象
    case 'receiveObj': {
      const { value } = p as TParams<'receiveObj'>
      if (value == null) return
      return <div>{receiveObjMap[value]}</div>
    }
    // 发送类型
    case 'sendType': {
      const { value } = p as TParams<'sendType'>
      if (value == null) return
      return <div>{sendTypeMap[value]}</div>
    }
    // 类型
    case 'type': {
      const { value } = p as TParams<'type'>
      if (value == null) return
      return <div>{typeMap[value]}</div>
    }
    // 操作
    case '操作': {
      return <ActionCell {...p} />
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

/** 消息模板 */
export const MsgManage = () => {
  useMsgManageList() //放在顶部 初始加载
  const gridRef = useBoundStore(v => v.gridRef)
  const loading = useBoundStore(v => v.request?.loading)
  const data = useBoundStore(v => v.request?.data)
  const page = useBoundStore(v => v.reqData.page)
  const size = useBoundStore(v => v.reqData.size)
  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 180,
      sortable: false,
      cellRenderer: Cell,
    }),
    [],
  )
  const columnDefs = useMemo(
    () =>
      [
        {
          field: 'messageId',
          headerName: '消息ID',
          flex: 0.1,
          minWidth: 114,
        },
        {
          field: 'title',
          headerName: '标题',
          flex: 1.5,
          minWidth: 180 * 1.5,
        },
        {
          field: 'type',
          headerName: '类型',
          flex: 0.1,
          minWidth: 128,
        },
        {
          field: 'sendType',
          headerName: '发送类型',
          flex: 0.1,
          minWidth: 114,
        },
        {
          field: 'enableFlag',
          headerName: '启用状态',
          flex: 0.1,
          minWidth: 114,
        },
        {
          field: 'channelType',
          headerName: '通知渠道',
          flex: 0.1,
          minWidth: 128,
        },
        {
          field: 'eventType',
          headerName: '事件',
        },
        {
          field: 'updateAt',
          headerName: '更新时间',
          flex: 0.1,
          minWidth: 166,
        },
        {
          field: '操作',
          flex: 0.01,
          width: 100,
          minWidth: 100,
          pinned: 'right',
        },
      ] satisfies TCol[],
    [],
  )

  // 分页器
  const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
    return {
      statusPanels: [
        {
          statusPanel: UnifiedPagination,
          statusPanelParams: UnifiedPagination.defineProps({
            current: page,
            pageSize: size,
            total: data?.total,
            onChange: (page, size) => {
              setReqData({ page, size })
              getData({ page, size })
            },
          }),
        },
      ],
    }
  }, [data?.total, getData, page, setReqData, size])

  // 清理，保留筛选条件
  useEffect(
    () => () =>
      useBoundStore.setState({ ...useBoundStore.getInitialState(), reqData: useBoundStore.getState().reqData }, true),
    [],
  )

  return (
    <div className={styles.box}>
      <div className={styles.header}>
        <Input.Search
          style={{ width: 300 }}
          placeholder="请输入消息标题"
          allowClear
          onSearch={value => {
            setReqData({ title: value })
            getData({ title: value })
          }}
        />
        <Button
          type="primary"
          onClick={() => {
            AddOrEditMsgDrawer.open({
              onSuccess: () => {
                getData()
              },
            })
          }}
        >
          添加消息
        </Button>
      </div>
      <div className={styles.main}>
        <CusAgGrid<IMsgList>
          ref={gridRef}
          loading={loading}
          rowData={data?.records}
          defaultColDef={defaultColDef}
          columnDefs={columnDefs}
          statusBar={statusBar}
        />
      </div>
      <popupSlot.Slot />
    </div>
  )
}
